package com.example.job;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author 郅占伟
 * @ClassName DataBaseBackup
 * @Description TODO
 * @Date 2024年07月10日
 * @Version: 1.0
 */
@Configuration
@Service
public class DataBaseBackup {
    //备份的数据库名
    @Value("${mysqlDataBase.name}")
    private String dbName;


    //用户名
    @Value("${spring.datasource.username}")
    private String username;


    //密码
    @Value("${spring.datasource.password}")
    private String password;


    //备份数据库文件地址
    @Value("${mysqlDataBase.url}")
    private String filePath;


    //ip地址
    @Value("${mysqlDataBase.ip}")
    private String ip;

    /**
     * @Description 数据库备份 每天凌晨0点执行一次备份：cron表达式：[0 0 0 * * ?]
     * @MethodName BarCodesDataMigration
     * @Date 15:01 2024/5/13
     */
    @Scheduled(cron = "0/10 * * * * *")
    public void configureTasks() {
        Date now = new Date();
        File uploadDir = new File(filePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String dataStr = filePath + File.separator + new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "_" + dbName + ".sql";
        String command = "mysqldump -h" + ip + " -u" + username + " -p" + password + " " + dbName + " -r " + dataStr;
        try {
            Runtime.getRuntime().exec(command);
            System.out.println("数据库备份成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库备份失败！");
        }
    }


}
